#pragma region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU Lesser General Public License.
/// </copyright>
#pragma endregion

#include "stdafx.h"

static double MillisecondsPerDay = 1.0 / (24 * 60 * 60 * 1000);

OSHBitmap::OSHBitmap() : _oshSource(NULL), _bitmapNumber(-1), _bitmapInfo(NULL)
{
	ATLTRACE_TS(atlTraceOSHBitmap, TraceLevel::Verbose,
		"OSHBitmap::OSHBitmap() : 0x%08X\r\n", this);
}

OSHBitmap::~OSHBitmap()
{
	ATLTRACE_TS(atlTraceOSHBitmap, TraceLevel::Verbose,
		"OSHBitmap::~OSHBitmap() : 0x%08X\r\n", this);
	Close();
}

bool OSHBitmap::IsOpened() const
{
	return _bitmapInfo != NULL;
}

HRESULT OSHBitmap::Initialize(OSHSource* source, int bitmapNumber, void* bitmapPtr, SYSTEMTIME* time)
{
	ATLTRACE_TS(atlTraceOSHBitmap, TraceLevel::Verbose,
		"OSHBitmap::Initialize([0x%08X], ISource: 0x%08X)\r\n", this, source);

	if(source == NULL || bitmapPtr == NULL) return E_INVALIDARG;

	_oshSource = source;
	_bitmapNumber = bitmapNumber;
	_bitmapInfo = reinterpret_cast<BITMAPINFOHEADER*>(bitmapPtr);
	_refTime = *time;

	return S_OK;
}

STDMETHODIMP OSHBitmap::get_Created(DATE* created)
{
	if(created == NULL)
		return E_POINTER;

	if(!IsOpened())
		return E_UNEXPECTED;

	ATLTRACE_TS(atlTraceOSHBitmap, TraceLevel::Verbose,
		"OSHBitmap::get_Created() = %04d-%02d-%02d %02d:%02d:%02d.%03d\r\n",
		_refTime.wYear, _refTime.wMonth, _refTime.wDay,
		_refTime.wHour, _refTime.wMinute, _refTime.wSecond, _refTime.wMilliseconds);

	COleDateTime refTime(_refTime.wYear, _refTime.wMonth, _refTime.wDay,
		_refTime.wHour, _refTime.wMinute, _refTime.wSecond);

	*created = refTime;
	*created += _refTime.wMilliseconds * MillisecondsPerDay;

	return S_OK;
}

STDMETHODIMP OSHBitmap::get_BitmapInfo(LONG* bitmapInfo)
{
	ATLTRACE_TS(atlTraceOSHBitmap, TraceLevel::Verbose,
		"OSHBitmap::get_BitmapInfo() : 0x%08X\r\n", _bitmapInfo);

	if(bitmapInfo == NULL)
		return E_POINTER;

	if(!IsOpened())
		return E_UNEXPECTED;

	*bitmapInfo = (LONG)(UINT_PTR)_bitmapInfo;

	return S_OK;
}

STDMETHODIMP OSHBitmap::Close()
{
	if(!IsOpened())
		return S_OK;

	ATLTRACE_TS(atlTraceOSHBitmap, TraceLevel::Verbose, "OSHBitmap::Close()\r\n");

	_oshSource->OnBitmapClose(*this);

	_bitmapInfo = NULL;
	return S_OK;
}

STDMETHODIMP OSHBitmap::Save(BSTR filePath)
{
	if(filePath == NULL)
		return E_POINTER;

	if(!IsOpened())
		return E_UNEXPECTED;

	return Utils::SaveBitmapFile(filePath, (BITMAPINFO*)_bitmapInfo);
}


